package com.wxd.framework.common.web.Interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UrlPathHelper;

import com.wxd.framework.common.FrameConstants;
import com.wxd.framework.common.web.session.SessionProvider;

/**
 * 
 * 上下文信息拦截器
 * 
 * 登录信息、权限信息等
 * @author wangxd
 *
 */
public class AdminContextInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private SessionProvider session;
	
	/**
	 * 登录url
	 */
	private String loginUrl;
	/**
	 * 被排除的url（不进行拦截的url）
	 */
	private String[] excludeUrls;
	
	private String processUrl;
	
	private String returnUrl;

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

	public void setExcludeUrls(String[] excludeUrls) {
		this.excludeUrls = excludeUrls;
	}
	
	public void setProcessUrl(String processUrl) {
		this.processUrl = processUrl;
	}

	public void setReturnUrl(String returnUrl) {
		this.returnUrl = returnUrl;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
		String uri = getUri(request);
		if (exclude(uri)) {
			return true;
		}
		
		Object user = session.getAttributeObject(request, FrameConstants.SESSON_KEY_CURRUSER);
		if (user == null) {
			response.sendRedirect(getLoginUrl(request));
			return false;
		}
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mav)
			throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}
	
	/**
	 * 获取登录url
	 * @param request
	 * @return
	 */
	private String getLoginUrl(HttpServletRequest request){
		StringBuilder buff = new StringBuilder();
		if (loginUrl.startsWith("/")) {
			String ctx = request.getContextPath();
			if (StringUtils.isNotBlank(ctx)) {
				buff.append(ctx);
			}
		}
		buff.append(loginUrl).append("?");
		buff.append(returnUrl).append("=").append(returnUrl);
		if (StringUtils.isNotBlank(processUrl)) {
			buff.append("&").append("processUrl").append("=").append(getProcessUrl(request));
		}
		return buff.toString();
	}
	
	private String getProcessUrl(HttpServletRequest request) {
		StringBuilder buff = new StringBuilder();
		if (loginUrl.startsWith("/")) {
			String ctx = request.getContextPath();
			if (!StringUtils.isBlank(ctx)) {
				buff.append(ctx);
			}
		}
		buff.append(processUrl);
		return buff.toString();
	}
	
	/**
	 * 判断是否为排除的url
	 * @param uri
	 * @return
	 */
	private boolean exclude(String uri) {
		if (excludeUrls != null) {
			for (String exc : excludeUrls) {
				if (exc.equals(uri)) {
					return true;
				}
			}
		}
		return false;
	}
	

	/**
	 * TODO  为什么一定要admin
	 * 获取当前Url
	 * @param request
	 * @return
	 * @throws IllegalStateException
	 */
	private String getUri(HttpServletRequest request) throws IllegalStateException {
		UrlPathHelper helper = new UrlPathHelper();
		String uri = helper.getOriginatingRequestUri(request);//  /demo-app/login.do
		int index = uri.lastIndexOf('/');
		if (index <= 0) {
			throw new IllegalStateException("uri格式不正确 " + uri);
		}
		return uri.substring(index);
	}
}
